//
//  BoxCostHeadView.m
//  XLDoctor
//
//  Created by longma on 2018/10/8.
//  Copyright © 2018年 XLH. All rights reserved.
//

#import "BloodSugarChartView.h"
#import "healthOV-Swift.h"

@interface BloodSugarChartView()<ChartViewDelegate,ChartAxisValueFormatter,ChartValueFormatter>
@property (nonatomic ,strong) LineChartView *chartView;
@property (nonatomic, strong) NSMutableArray *dataEntryArray;//点数组
@property (weak, nonatomic) IBOutlet UIView *chartViewBg;
@property (nonatomic ,strong) UIColor *themeColor;//主题颜色
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UIImageView *emptyImageView;
@property (nonatomic, assign) BOOL isFasting;
@property (nonatomic ,strong) UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UILabel *lastResultTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *sevenAverageTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *monthlyAverageTitleLabel;

@end

@implementation BloodSugarChartView


- (void)awakeFromNib{
    [super  awakeFromNib];
    
    self.lastResultTitleLabel.adjustsFontSizeToFitWidth = true;
    self.sevenAverageTitleLabel.adjustsFontSizeToFitWidth = true;
    self.monthlyAverageTitleLabel.adjustsFontSizeToFitWidth = true;

    [self.fastingButton setTitleColor:UIColor.mj_grayColor forState:0];
    [self.fastingButton setTitleColor:UIColor.mj_appColor forState:UIControlStateSelected];
    
    [self.postprandialButton setTitleColor:UIColor.mj_grayColor forState:0];
    [self.postprandialButton setTitleColor:UIColor.mj_appColor forState:UIControlStateSelected];
    
    //
    //得添加在scrollView 上面不然会造成手势冲突
    UIScrollView *scrollView=[[UIScrollView alloc] init];
    
    //scrollView.contentSize=CGSizeMake(SCREEN_WIDTH - 40, 200);
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.pagingEnabled = NO;//控制控件是否整页翻动
    scrollView.showsHorizontalScrollIndicator = false;
    scrollView.scrollEnabled = false;
    self.scrollView = scrollView;
    
    [self.chartViewBg addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.chartViewBg);
    }];
    
    [scrollView addSubview:self.chartView];
    [self.chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.chartViewBg);
    }];
    
    self.themeColor = MJUIColorFromHex(0xFA6450);
    
    [self.fastingButton setSelected:true];
    [self.postprandialButton setSelected:false];
}

- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis{
//    NSLog(@"=====value===========%lf",value);
    if(self.dataArray.count > 0){
        
        int intValue = (int)value;
        if(intValue == value && intValue >= 0 && self.dataArray.count > intValue){
//            NSLog(@"=====intValue===========%d",intValue);
            MJBloodSugarModel *rmodel = self.dataArray[intValue];
            NSString *time = [rmodel.detectionDateTime mj_stringConvertToFormatStringByFormat:@"M/d" OriginalFormat:MJUIDateFormat];
//            return [@"\n" stringByAppendingString:time];//x轴数据
            return time;//x轴数据
        }
    }
    return @"";
}

/// 自定义value
- (NSString *)stringForValue:(double)value entry:(ChartDataEntry *)entry dataSetIndex:(NSInteger)dataSetIndex viewPortHandler:(ChartViewPortHandler *)viewPortHandler {
    
//    NSLog(@"MJLog============dataSetIndex===========%ld",dataSetIndex);
    MJBloodSugarModel *model = self.dataArray[(int)entry.x];
    return model.bloodGlucoseChartString;
    //对num取整
//    CGFloat i = roundf(entry.y);
//    if (i == entry.y) {
//        return @(entry.y).description;
//    }else{
//        return [NSString mj_stringWithCGFloat:entry.y decimal:2];
//    }
}

- (void)processData:(NSArray *)detectionArray{
    
//    if(detectionArray.count > 0){
        
        NSMutableArray *modelArray = [NSMutableArray array];
        NSMutableArray *timeArray = [NSMutableArray array];
        
        //去日期最新的检测数据
        for (MJBloodSugarModel *model in detectionArray) {
            NSString *timeString = [model.detectionDateTime mj_stringConvertToFormatStringByFixFormat:MJUIDateFormat2];
            if(![timeArray containsObject:timeString]){
                [modelArray addObject:model];
                [timeArray addObject:timeString];
            }
        }
        
        [self.dataArray removeAllObjects];
        
        //先处理原数据
        for (int i = 0; i < modelArray.count; i++)
        {
            MJBloodSugarModel *rmodel = modelArray[i];
            [self.dataArray insertObject:rmodel atIndex:0];
        }
        
        //重新排列点数据（0 开始）
        [self.dataEntryArray removeAllObjects];
        for (int i = 0; i < self.dataArray.count; i++)
        {
            
            MJBloodSugarModel *rmodel = self.dataArray[self.dataArray.count - 1 - i];
            
            CGFloat avgValue = rmodel.bloodGlucose;
            
            //防止最顶部线变细avgValue*0.995
            ChartDataEntry *chartDataEntry = [[ChartDataEntry alloc] initWithX:self.dataArray.count - 1 - i y:avgValue icon: nil];
            
            
            [self.dataEntryArray insertObject:chartDataEntry atIndex:0];
        }
        
        [self replaceEntries];
        
//    }
    
    if(detectionArray.count == 0){
        self.emptyImageView.hidden = false;
        self.chartView.hidden = true;
    }else{
        self.emptyImageView.hidden = true;
        self.chartView.hidden = false;
    }
}
- (void)initData:(NSString *)period {
    if([period isEqualToString:@"Fasting"]){
        self.isFasting = true;
    }else{
        self.isFasting = false;
    }
    //移除添加
    [self.chartView removeFromSuperview];
    self.chartView = nil;
    
    [self.scrollView addSubview:self.chartView];
    [self.chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.chartViewBg);
    }];
    //

    self.chartView.viewPortHandler.isFasting = self.isFasting;
    
    MJCommonModel *parms = [[MJCommonModel alloc]init];
    parms.patientId = self.patientId;
    parms.period = period;
    NSArray *array = [WCBDHelper.shared mj_getBloodSugarArrayWithParm:parms];
    [self processData:array];
    if(array.count){
        
        MJBloodSugarModel *lastModel = array[0];
        self.lastResultLabel.text = lastModel.bloodGlucoseChartString;
        
        //获取最近7日日期
        NSMutableArray *sevenDateArray = [NSDate getCurrentWeeksWithFirstDiff:-6 lastDiff:0];
        
        NSString *maxDate = [[[NSDate new] mj_expectDateWithYear:0 month:0 day:1] mj_dateConvertToStringByFormat:MJUIDateFormat2];
        MJCommonModel *parms = [[MJCommonModel alloc]init];
        parms.patientId = self.patientId;
        parms.period = period;
        parms.minDate = sevenDateArray[0];
        parms.maxDate = maxDate;
        NSArray *sevenDetectionDataArray = [WCBDHelper.shared mj_getBloodSugarArrayWithParm:parms];
        if(sevenDetectionDataArray.count){
            NSMutableArray *sevenDetectionArray = [NSMutableArray array];
            NSMutableArray *timeArray = [NSMutableArray array];
            
            CGFloat totalBloodGlucose = 0;
            for (MJBloodSugarModel *model in sevenDetectionDataArray) {
                NSString *timeString = [model.detectionDateTime mj_stringConvertToFormatStringByFixFormat:MJUIDateFormat2];
                if(![timeArray containsObject:timeString]){
                    [sevenDetectionArray addObject:model];
                    [timeArray addObject:timeString];
                    totalBloodGlucose = totalBloodGlucose + model.bloodGlucose;
                }
            }
            if(totalBloodGlucose > 0){
                self.sevenAverageLabel.text = [NSString mj_stringWithCGFloat:totalBloodGlucose/sevenDetectionArray.count decimal:2];
            }else{
                self.sevenAverageLabel.text = @"--";
            }
            NSLog(@"MJLog=======================%@",sevenDetectionArray);
        }else{
            self.sevenAverageLabel.text = @"--";
        }
        
        //获取最近30天日期
        NSMutableArray *thirtyDateArray = [NSDate getCurrentWeeksWithFirstDiff:-29 lastDiff:0];
        MJCommonModel *thirtyParms = [[MJCommonModel alloc]init];
        thirtyParms.patientId = self.patientId;
        thirtyParms.period = period;
        thirtyParms.minDate = thirtyDateArray[0];
        thirtyParms.maxDate = [[[NSDate new] mj_expectDateWithYear:0 month:0 day:1] mj_dateConvertToStringByFormat:MJUIDateFormat2];
        NSArray *thirtyDetectionDataArray = [WCBDHelper.shared mj_getBloodSugarArrayWithParm:thirtyParms];
        if(thirtyDetectionDataArray.count){
            NSMutableArray *thirtyDetectionArray = [NSMutableArray array];
            NSMutableArray *timeArray = [NSMutableArray array];
            
            CGFloat totalBloodGlucose = 0;
            for (MJBloodSugarModel *model in thirtyDetectionDataArray) {
                NSString *timeString = [model.detectionDateTime mj_stringConvertToFormatStringByFixFormat:MJUIDateFormat2];
                if(![timeArray containsObject:timeString]){
                    [thirtyDetectionArray addObject:model];
                    [timeArray addObject:timeString];
                    totalBloodGlucose = totalBloodGlucose + model.bloodGlucose;
                }
            }
            if(totalBloodGlucose > 0){
                self.monthlyAverageLabel.text = [NSString mj_stringWithCGFloat:totalBloodGlucose/thirtyDetectionArray.count decimal:2];
            }else{
                self.monthlyAverageLabel.text = @"--";
            }
            NSLog(@"MJLog=======================%@",thirtyDetectionArray);
        }else{
            self.monthlyAverageLabel.text = @"--";
        }
    }else{
        self.lastResultLabel.text = @"--";
        self.sevenAverageLabel.text = @"--";
        self.monthlyAverageLabel.text = @"--";
    }
    
}
- (void)setPatientId:(NSString *)patientId {
    _patientId = patientId;
    
    [self initData:@"Fasting"];

}



- (IBAction)handleFastingButtonClick:(UIButton *)sender {
    [self.fastingButton setSelected:true];
    [self.postprandialButton setSelected:false];
    
    [self initData:@"Fasting"];

}
- (IBAction)handlePostprandialButtonClick:(UIButton *)sender {
    [self.fastingButton setSelected:false];
    [self.postprandialButton setSelected:true];
    
    [self initData:@"Postprandial"];

}

#pragma mark - 懒加载
- (LineChartView *)chartView{
    if (_chartView == nil) {//mjtu
        
        _chartView = [[LineChartView alloc]initWithFrame:CGRectZero];
        _chartView.viewPortHandler.detectionType = DetectionTypeBloodSugar;
        _chartView.extraRightOffset = 25;
        _chartView.extraLeftOffset = 25;
        _chartView.extraBottomOffset = 10;
        _chartView.extraTopOffset = 50;
//        _chartView.extraTopOffset = 2;
//        _chartView.backgroundColor = UIColor.grayColor;
        _chartView.noDataText = @"";
        _chartView.delegate = self;//代理
        //[_chartView setScaleEnabled:YES];//放大缩小
        _chartView.chartDescription.enabled = NO;// 设置折线图描述
        _chartView.scaleYEnabled = NO;//垂直方向放大缩小
        _chartView.scaleXEnabled = NO;//水平方向放大缩小
//        _chartView.dragEnabled = YES;//允许拖拽
        _chartView.dragXEnabled = true;
        _chartView.dragYEnabled = NO;//不允许拖拽Y
        
        _chartView.highlightPerDragEnabled = false;
        _chartView.doubleTapToZoomEnabled = false;
        _chartView.pinchZoomEnabled = NO;//是否支持X轴、Y轴同时缩放，如果是YES ，则代表支持同时缩放。
        _chartView.dragDecelerationEnabled = YES;//启动拖拽图标
        _chartView.dragDecelerationFrictionCoef = 0.9;//拖拽后是否有惯性效果(0~1)，数值越小，惯性越不明显
        _chartView.drawGridBackgroundEnabled = NO;//是否要画网格
        _chartView.legend.enabled = NO;// 设置折线图图例 这个Bool属性是设置要不要显示图例的，看到上图底部的"-- DataSet 1"
//        [_chartView.viewPortHandler setMaximumScaleX:3.5];//最大缩放max
        
        // 设置 X 轴样式
        ChartXAxis *xAxis = _chartView.xAxis;
        xAxis.labelPosition = XAxisLabelPositionBottom;// 设置 X 轴的显示位置，默认是显示在上面的
        xAxis.valueFormatter = self;
        xAxis.axisLineWidth = 1;// 设置 X 轴线宽
        xAxis.axisLineColor = [UIColor mj_colorWithHexString:@"#E5E5E5"];
        xAxis.labelFont = [UIFont systemFontOfSize:10.0f]; // 不强制绘制指定数量的 label
        xAxis.labelTextColor = UIColor.mj_lightGrayColor; // label 文字颜色
        xAxis.granularityEnabled = NO;// 设置重复的值不显示
        
        xAxis.drawGridLinesEnabled = YES;// 绘制网格线(竖的线)
        xAxis.gridColor = [UIColor mj_colorWithHexString:@"#E5E5E5"]; // 网格线颜色
        xAxis.gridLineWidth = 1;// 网格线颜色
        xAxis.granularity = 1; //间距

        
        ChartYAxis *leftAxis = _chartView.rightAxis;// 获取左边 Y 轴
        leftAxis.drawAxisLineEnabled = NO;
        leftAxis.drawLabelsEnabled = NO;
        leftAxis.drawGridLinesEnabled = NO;// 不绘制网格线

        _chartView.leftAxis.enabled = NO;// 设置 Y 轴样式不绘制右边轴


    }
    return _chartView;
}
#pragma mark 图表中被选中
-(void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight {
    
//    //修改选中圆点大小
    LineChartDataSet *set1 = (LineChartDataSet *)_chartView.data.dataSets[0];
    for (ChartDataEntry *mentry in set1.entries) {
        mentry.icon = nil;
    }
    UIImage *image = [UIImage imageNamed:@"bg_dianhuang"];
    if(self.isFasting){
        image = [UIImage imageNamed:@"bg_dian_xuetan"];
    }
    entry.icon = image;
    
    //
    NSInteger index = (NSInteger)entry.x;
    _chartView.viewPortHandler.gluClickIndex = index;
    _chartView.viewPortHandler.isFasting = self.isFasting;

    // 重新渲染表格
    [_chartView.data notifyDataChanged];
    [_chartView notifyDataSetChanged];


}
#pragma mark ************** 画点数据
- (void)replaceEntries{
    
    UIColor *themeColor = MJUIColorFromHex(0xF59B18);
    if(self.isFasting){
        themeColor = MJUIColorFromHex(0xFA6450);
    }

    LineChartDataSet *set1 = nil;
    if (_chartView.data.dataSetCount > 0)
    {
        set1 = (LineChartDataSet *)_chartView.data.dataSets[0];
        set1.drawVerticalHighlightIndicatorEnabled = true;//重新加载时候把选中取消高亮线
        [set1 setColor:themeColor];//折线颜色
        [set1 setCircleColor:themeColor];//圆圈颜色

        [set1 replaceEntries: self.dataEntryArray];
        
        
        //默认选中最后一个
        ChartHighlight *chartHighlight = [[ChartHighlight alloc]initWithX:self.dataEntryArray.count-1 dataSetIndex:0 stackIndex:0];
        [_chartView highlightValue:chartHighlight];
        [self chartValueSelected:_chartView entry:self.dataEntryArray.lastObject highlight:chartHighlight];

       
        _chartView.scaleXEnabled = NO;//水平方向放大缩小
        //最大缩放值 最小缩放值  y轴不缩放 minScl maxScl根据实际情况调整
        if(_chartView.data.entryCount > 7){
            //四舍五入 ceil round
            CGFloat scaleF = _chartView.data.entryCount/7.0;
            [_chartView setScaleMinima:scaleF scaleY:1];
        }else{
            //重新设置缩放无效
            [_chartView setScaleMinima:1 scaleY:1];
        }
        
    }
    else
    {
        
        set1 = [[LineChartDataSet alloc] initWithEntries:self.dataEntryArray label:@"DataSet 1"];
        set1.drawValuesEnabled = YES;//显示顶部值
        set1.mode = LineChartModeCubicBezier;
        [set1 setColor:themeColor];//折线颜色
        set1.lineWidth = 4.0;//折线宽度
        [set1 setCircleColor:themeColor];//圆圈颜色
        set1.circleRadius = 5;//圆圈半径
        set1.drawCircleHoleEnabled = true;//使能空心圆
        set1.drawIconsEnabled = YES;//允许画 icon 图片
        set1.valueFont = MJUIFontBebasMake(12);
        set1.valueTextColor = UIColor.mj_grayColor;
        set1.valueFormatter = self;
        set1.axisDependency = AxisDependencyRight;//依赖右轴（重要）
        
        //高亮
        set1.highlightLineDashLengths = @[@8.f, @4.f];//选中为虚线
        set1.highlightColor = UIColor.clearColor;
        set1.highlightLineWidth = 1;
        set1.drawHorizontalHighlightIndicatorEnabled = false; //隐藏高亮水平线
//        set1.drawVerticalHighlightIndicatorEnabled = false; //隐藏高亮水平线

        NSMutableArray *dataSets = [[NSMutableArray alloc] init];
        [dataSets addObject:set1];
        
        LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
        
        _chartView.data = data;
        
        //最大缩放值 最小缩放值  y轴不缩放 minScl maxScl根据实际情况调整
        if(_chartView.data.entryCount > 7){
            //四舍五入 ceil round
            CGFloat scaleF = _chartView.data.entryCount/7.0;
            CGFloat scaleMin = ceil(_chartView.data.entryCount/7.0);
            [_chartView setScaleMinima:scaleF scaleY:1];

        }else{
            [_chartView setScaleMinima:1 scaleY:1];
            
        }
        
        //移动到最右边
        if(_chartView.data.xMax){
            [_chartView moveViewToX:_chartView.data.xMax];
        }
        //默认选中最后一个
        ChartHighlight *chartHighlight = [[ChartHighlight alloc]initWithX:self.dataEntryArray.count-1 dataSetIndex:0 stackIndex:0];
        [_chartView highlightValue:chartHighlight];
        
        [self chartValueSelected:_chartView entry:self.dataEntryArray.lastObject highlight:chartHighlight];
     
    }

    //刷新数据
    [_chartView.data notifyDataChanged];
    [_chartView notifyDataSetChanged];
    

    
}

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)dataEntryArray{
    if(!_dataEntryArray){
        _dataEntryArray = [NSMutableArray array];
    }
    return _dataEntryArray;
}

@end
